package com.vcc.boss.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckSafe;
import cn.idev.excel.ExcelWriter;
import cn.idev.excel.write.metadata.WriteSheet;
import com.mybatisflex.core.paginate.Page;
import com.vcc.boss.core.component.OssComponent;
import com.vcc.core.annotations.CurrentUserId;
import com.vcc.core.annotations.RestPack;
import com.vcc.core.derive.admin.DeriveRechargeLog;
import com.vcc.core.exception.ProgramException;
import com.vcc.core.util.ExportUtil;
import com.vcc.core.util.RegexUtil;
import com.vcc.data.entity.Currency;
import com.vcc.data.entity.RechargeLog;
import com.vcc.service.boss.request.rechargeLog.AuditOrderDto;
import com.vcc.service.boss.response.rechargeLog.RechargeLogVoBoss;
import com.vcc.service.service.*;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Log4j2
@RestController
@RequestMapping("rechargeLog")
public class RechargeLogController {

    @Autowired
    private RechargeLogService rechargeLogService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private UserService userService;
    @Autowired
    private OssComponent ossComponent;
    @Autowired
    private BossUserService bossUserService;
    @Autowired
    private CurrencyService currencyService;


    @RestPack
    @SaCheckPermission(value = "wallet:recharge-log:list:view")
    @SaCheckLogin
    @GetMapping("paging")
    public Page<RechargeLogVoBoss> paging(
            @CurrentUserId Long userId,
            Integer pageNumber,
            Integer pageSize,
            Long targetUserId,
            Integer useFlag,
            Integer status,
            String remark,
            String startDate,
            Long dealerId,
            String endDate
    ) {
        Page<RechargeLog> paging = rechargeLogService.paging(
                userId,
                Page.of(
                        pageNumber == null || pageNumber < 1 ? 1 : pageNumber,
                        pageSize == null || pageSize < 1 ? 20 : pageSize
                ),
                targetUserId,
                useFlag,
                status,
                remark,
                startDate,
                endDate,
                dealerId);
        if (paging.getRecords().isEmpty()) {
            return Page.of(paging.getPageNumber(), paging.getPageSize());
        }
        return paging.map(RechargeLogVoBoss::new);
    }

    @GetMapping("derive")
    @SaCheckPermission(value = "wallet:recharge-log:list:derive")
    public void derive(
            @CurrentUserId Long userId,
            Long targetUserId,
            Integer useFlag,
            Integer status,
            String remark,
            String startDate,
            String endDate,
            Long dealerId,
            HttpServletResponse response
    ) {
        if (RegexUtil.checkStringIsNull(startDate)) {
            throw new ProgramException("请选择开始时间");
        }
        if (RegexUtil.checkStringIsNull(endDate)) {
            throw new ProgramException("请选择结束时间");
        }
        Long pages = 1L;
        Page<RechargeLog> paging;
        String fileName = System.currentTimeMillis() + "充值订单.xlsx";
        ExcelWriter excelWriter;
        try {
            ExportUtil.setExcelResponseHeaders(response, fileName);
            excelWriter = ExportUtil.createExcelWriter(response.getOutputStream(), DeriveRechargeLog.class);
        } catch (Exception e) {
            log.error("导出充值订单数据失败", e);
            throw new ProgramException("导出充值订单数据失败");
        }
        WriteSheet writeSheet = ExportUtil.createWriteSheet("充值订单", DeriveRechargeLog.class);
        List<Currency> currencyList = currencyService.list();
        try {
            do {
                paging = rechargeLogService.paging(userId, Page.of(pages++, 500), targetUserId, useFlag, status, remark, startDate, endDate, dealerId);
                List<DeriveRechargeLog> list = paging.getRecords().stream().map(it -> {
                    Currency currency = currencyList.stream().filter(c -> c.getId().equals(it.getCurrencyId())).findFirst().orElse(null);
                    return DeriveRechargeLog.builder()
                            .id(it.getId())
                            .orderId(it.getOrderId())
                            .useFlag(it.getUseFlag())
                            .requestDate(it.getRequestDate())
                            .account(StringUtils.isBlank(it.getAccount()) ? "-" : it.getAccount())
                            .amount(it.getAmount())
                            .remittanceAmount(it.getRemittanceAmount())
                            .remittanceCurrency(it.getRemittanceCurrency())
                            .hash(it.getVoucher())
                            .network("TRC-20")
                            .remittanceAddress(it.getRemittanceAddress())
                            .rechargeAddress(it.getRechargeAddress())
                            .remark(it.getRemark())
                            .status(it.getStatus())
                            .auditDate(it.getAuditDate())
                            .auditAccount(StringUtils.isBlank(it.getAuditAccount()) ? "-" : it.getAuditAccount())
                            .currencyName(currency.getCode())
                            .dealerAccount(StringUtils.isBlank(it.getDealerAccount()) ? "-" : it.getDealerAccount())
                            .build();
                }).toList();
                ExportUtil.writeData(excelWriter, writeSheet, list);
                list = null;
            } while (!(pages).equals(paging.getTotalPage() + 1));
        }catch (Exception e){
            log.error("导出失败",e);
            throw new ProgramException("导出失败");
        }
        ExportUtil.closeExcelWriter(excelWriter);

    }

    @RestPack
    @SaCheckPermission(value = "wallet:recharge-log:list:audit")
    @PostMapping("audit")
    @SaCheckSafe("CLIENT_ORDER_AUDIT")
    public Boolean audit(
            @RequestBody @Validated AuditOrderDto auditOrderDto
    ) {
        return rechargeLogService.audit(auditOrderDto);
    }
}
